package org.kalai.unifypay.zhongxpay;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.kalai.unifypay.Constant;
import org.kalai.unifypay.util.CommonUtil;
import org.kalai.unifypay.util.DateUtil;
import org.kalai.unifypay.util.HttpUtil;

/**
 * 中信银行支付接口
 * @author Renne66
 *
 */
public final class ZhongxPay {
	private static final Logger logger = Logger.getLogger(ZhongxPay.class);
	
	public static Map<String, Object> wxBarcodePay(String tranxSN, String authCode, long transAmt, String body){
		Map<String, Object> params = new TreeMap<>();
		params.put("service", "unified.trade.micropay");
		params.put("mch_id", Constant.ZX_MCHID);
		params.put("out_trade_no", tranxSN);
		params.put("body", body);
		params.put("total_fee", transAmt);
		params.put("mch_create_ip", "115.231.102.206");
		params.put("auth_code", authCode);
		params.put("nonce_str",DateUtil.formatNow("MMddHHmmssSSSS"));
		Element msgEl =  post(params);
		String status = msgEl.elementText("status");
		if (!"0".equals(status))  return CommonUtil.createRespMap(status, msgEl.elementText("message"));
		String resultCode = msgEl.elementText("result_code");
		if ("0".equals(resultCode)) return CommonUtil.createRespMap("00", "交易成功");
		String needQuery = msgEl.elementText("need_query");
		if ("Y".equals(needQuery)) return CommonUtil.createRespMap("01", "支付中");
		wxReverse(tranxSN);
		return CommonUtil.createRespMap("10", "交易失败");
	}
	
	public static Map<String, Object> wxScancodePay(String tranxSN, String notifyUrl, long transAmt, String body){
		Map<String, Object> params = new TreeMap<>();
		params.put("service", "pay.weixin.native");
		params.put("mch_id", Constant.ZX_MCHID);
		params.put("out_trade_no", tranxSN);
		params.put("body", body);
		params.put("total_fee", transAmt);
		params.put("mch_create_ip", "115.231.102.206");
		params.put("notify_url", notifyUrl);
		params.put("nonce_str",DateUtil.formatNow("MMddHHmmssSSSS"));
		Element msgEl =  post(params);
		String status = msgEl.elementText("status");
		if (!"0".equals(status))  return CommonUtil.createRespMap(status, msgEl.elementText("message"));
		String resultCode = msgEl.elementText("result_code");
		if (!"0".equals(resultCode)) return CommonUtil.createRespMap(msgEl.elementText("err_code"), msgEl.elementText("err_msg"));
		String payResult = msgEl.elementText("pay_result");
		if ("0".equals(payResult)){
			Map<String, Object> map = CommonUtil.createRespMap("00", "交易成功");
			map.put("codeUrl", msgEl.elementText("code_url"));
			return map;
		}
		return CommonUtil.createRespMap(payResult, msgEl.elementText("pay_info"));
	}
	
	public static Map<String, Object> wxGzPay(String tranxSN, String wxOpenid, String notifyUrl, String returnUrl, long transAmt, String body){
		Map<String, Object> params = new TreeMap<>();
		params.put("service", "pay.weixin.jspay");
		params.put("mch_id", Constant.ZX_MCHID);
		params.put("out_trade_no", tranxSN);
		params.put("body", body);
		params.put("sub_openid", wxOpenid);
		params.put("total_fee", transAmt);
		params.put("mch_create_ip", "115.231.102.206");
		params.put("notify_url", notifyUrl);
		params.put("callback_url", returnUrl);
		params.put("nonce_str",DateUtil.formatNow("MMddHHmmssSSSS"));
		Element msgEl =  post(params);
		String status = msgEl.elementText("status");
		if (!"0".equals(status))  return CommonUtil.createRespMap(status, msgEl.elementText("message"));
		String resultCode = msgEl.elementText("result_code");
		if (!"0".equals(resultCode)) return CommonUtil.createRespMap(msgEl.elementText("err_code"), msgEl.elementText("err_msg"));
		Map<String, Object> map = CommonUtil.createRespMap("00", "待支付");
		map.put("codeUrl", "https://pay.swiftpass.cn/pay/jspay?token_id=" + msgEl.elementText("token_id") + "&showwxtitle=1");
		return map;
	}
	
	public static void getSettFile(String settleDate, String filePath){
		Map<String, Object> params = new TreeMap<>();
		params.put("service", "pay.bill.merchant");
		params.put("bill_date", settleDate);
		params.put("bill_type", "SUCCESS");
		params.put("mch_id", Constant.ZX_MCHID);
		params.put("nonce_str",DateUtil.formatNow("MMddHHmmssSSSS"));
		params.put("sign", ZhongxUtil.getMd5Sign(params));
		String content = HttpUtil.sendHttpsPost("https://download.swiftpass.cn/gateway", ZhongxUtil.getXmlData(params));
		File file =new File(filePath);
		try (FileOutputStream fos = new FileOutputStream(file)){
			if (!file.exists()) file.createNewFile();
			byte[] contentInBytes = content.getBytes();
			fos.write(contentInBytes);
			fos.flush();
			fos.close();
		} catch (IOException e) {
			logger.error(e);
		}
		
	}
	
	public static Map<String, Object> wxReverse(String tranxSN){
		Map<String, Object> params = new TreeMap<>();
		params.put("service", "unified.micropay.reverse");
		params.put("mch_id", Constant.ZX_MCHID);
		params.put("out_trade_no", tranxSN);
		params.put("nonce_str",DateUtil.formatNow("MMddHHmmssSSSS"));
		Element msgEl = post(params);
		String status = msgEl.elementText("status");
		if (!"0".equals(status))  return CommonUtil.createRespMap(status, msgEl.elementText("message"));
		String resultCode = msgEl.elementText("result_code");
		if (!"0".equals(resultCode)) return CommonUtil.createRespMap(msgEl.elementText("err_code"), msgEl.elementText("err_msg"));
		return CommonUtil.createRespMap("00", "关单成功");
	}
	
	public static Map<String, Object> queryOrder(String tranxSN){
		Map<String, Object> params = new TreeMap<>();
		params.put("service", "unified.trade.query");
		params.put("mch_id", Constant.ZX_MCHID);
		params.put("out_trade_no", tranxSN);
		params.put("nonce_str",DateUtil.formatNow("MMddHHmmssSSSS"));
		Element msgEl =  post(params);
		String status = msgEl.elementText("status");
		if (!"0".equals(status))  return CommonUtil.createRespMap(status, msgEl.elementText("message"));
		String resultCode = msgEl.elementText("result_code");
		if (!"0".equals(resultCode)) return CommonUtil.createRespMap(msgEl.elementText("err_code"), msgEl.elementText("err_msg"));
		String tradeState = msgEl.elementText("trade_state");
		return CommonUtil.createRespMap("SUCCESS".equals(tradeState) ? "00" : "xx", tradeState);
	}
	
	private static Element post(Map<String, Object> params){
		params.put("sign", ZhongxUtil.getMd5Sign(params));
		logger.info("发送中信交易请求："+params.get("out_trade_no"));
		String ret = HttpUtil.sendHttpsPost(Constant.ZX_URL, ZhongxUtil.getXmlData(params));
		logger.info("接收中信交易请求："+params.get("out_trade_no"));
		try {
			Document reqDoc = DocumentHelper.parseText(ret);
			return reqDoc.getRootElement();
		} catch (DocumentException e) {
			logger.error(ret);
			logger.error(e);
			return null;
		}
		
	}
	
	public static void main(String[] args) {
//		System.out.println(wxBarcodePay("201608251724", "130056451791963659", 1, "商品OK的"));
//		String notifyUrl = "http://renne66.imwork.net:28798/unifypay/ZhongxNotify";
//		System.out.println(wxScancodePay("201608241146", notifyUrl , 2, "测试商品"));
//		System.out.println(wxGzPay("20160926103000", "o4N61jlHuxewUUFKDO-m_s7TLZWc", Constant.ZX_NOTIFY_URL, "", 10, "测试商品"));
//		System.out.println(wxReverse("201608251574"));
//		System.out.println(queryOrder("201608251574"));
		getSettFile("20160926", "d:\\zx0926.TXT");
	}
}
